package com.archstoday.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.BaseEntity;
import com.base.activity.BaseActivity;
import com.base.http.common.BaseHttpClient;
import com.base.utils.MySharedPreferencesMgr;

/**
 * 基础页面类-支持滑动
 */
public class AsScrollBaseActivity extends BaseActivity {

    public BaseApp mApp;

    //手指上下滑动时的最小速度
    private static final int YSPEED_MIN = 1000;

    //手指向右滑动时的最小距离
    private static final int XDISTANCE_MIN = 50;

    //手指向上滑或下滑时的最小距离
    private static final int YDISTANCE_MIN = 100;

    //记录手指按下时的横坐标。
    private float xDown;

    //记录手指按下时的纵坐标。
    private float yDown;

    //记录手指移动时的横坐标。
    private float xMove;

    //记录手指移动时的纵坐标。
    private float yMove;

    //用于计算手指滑动的速度。
    private VelocityTracker mVelocityTracker;

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        createVelocityTracker(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDown = event.getRawX();
                yDown = event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                xMove = event.getRawX();
                yMove= event.getRawY();
                //滑动的距离
                int distanceX = (int) (xMove - xDown);
                int distanceY= (int) (yMove - yDown);
                //获取顺时速度
                int ySpeed = getScrollVelocity();
                //关闭Activity需满足以下条件：
                //1.x轴滑动的距离>XDISTANCE_MIN
                //2.y轴滑动的距离在YDISTANCE_MIN范围内
                //3.y轴上（即上下滑动的速度）<XSPEED_MIN，如果大于，则认为用户意图是在上下滑动而非左滑结束Activity
                if(distanceX > XDISTANCE_MIN &&(distanceY<YDISTANCE_MIN&&distanceY>-YDISTANCE_MIN)&& ySpeed < YSPEED_MIN) {
                    appFinish();
                }
                break;
            case MotionEvent.ACTION_UP:
                recycleVelocityTracker();
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    /**
     * 创建VelocityTracker对象，并将触摸界面的滑动事件加入到VelocityTracker当中。
     *
     * @param event
     *
     */
    private void createVelocityTracker(MotionEvent event) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
    }

    /**
     * 回收VelocityTracker对象。
     */
    private void recycleVelocityTracker() {
        mVelocityTracker.recycle();
        mVelocityTracker = null;
    }

    /**
     *
     * @return 滑动速度，以每秒钟移动了多少像素值为单位。
     */
    private int getScrollVelocity() {
        mVelocityTracker.computeCurrentVelocity(1000);
        int velocity = (int) mVelocityTracker.getYVelocity();
        return Math.abs(velocity);
    }

    @Override
    protected void initView(Bundle bundle) {
        mApp = (BaseApp) getApplication();
    }

    @Override
    protected void initData(Bundle bundle) {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {

    }

    @Override
    protected void onError(Throwable error, BaseHttpClient client) {
        new Thread() {
            @Override
            public void run() {
                new Handler(Looper.getMainLooper()).post(runnable);
            }
        }.start();
    }

    @Override
    protected void intentState(boolean state) {

    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            showToast(R.string.intent_error);
        }
    };

    public void getEvent(String e, String pageType) {
        initParameter();
        mParams.put("e", e);
        mParams.put("accountId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, null));
        mParams.put("deviceId", mApp.getDeviceID(mContext));
        mParams.put("platform", "android");
        mParams.put("appId", "200000");
        mParams.put("pageType", pageType);

        sendGetRequest(mApp.EVENT_URL, "event", mParams, BaseEntity.class);
    }

    public void getEvent(String e, String pageType, String info) {
        initParameter();
        mParams.put("e", e);
        mParams.put("accountId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, null));
        mParams.put("deviceId", mApp.getDeviceID(mContext));
        mParams.put("platform", "android");
        mParams.put("appId", "200000");
        mParams.put("pageType", pageType);
        mParams.put("info", info);

        sendGetRequest(mApp.EVENT_URL, "event", mParams, BaseEntity.class);
    }

    /**
     * 底部分享栏
     */
    private Dialog mShareDialog;
    public void setDialog() {
        mShareDialog = new Dialog(this, R.style.BottomDialog);
        View view = LayoutInflater.from(this).inflate(
                R.layout.layout_share, null);
        //初始化视图
        view.findViewById(R.id.share_wx_btn).setOnClickListener(click);
        view.findViewById(R.id.share_group_btn).setOnClickListener(click);
        view.findViewById(R.id.share_link_btn).setOnClickListener(click);
        view.findViewById(R.id.share_cancel_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismissShare();
            }
        });
        mShareDialog.setContentView(view);
        Window dialogWindow = mShareDialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = 0; // 新位置Y坐标
        lp.width = (int) getResources().getDisplayMetrics().widthPixels; // 宽度
        view.measure(0, 0);
        lp.height = view.getMeasuredHeight();

        lp.alpha = 9f; // 透明度
        dialogWindow.setAttributes(lp);
        mShareDialog.show();
    }

    public void dismissShare() {
        if (mShareDialog != null) {
            mShareDialog.dismiss();
        }
    }
}